<template>
	<view>
		<up-form @submit.prevent="onSubmit">
			<up-form-item :label="editUser.editName" borderBottom labelWidth='120rpx' style="padding-left: 30rpx;">
				<up-input v-model="editUser.currentValue" :placeholder="editUser.placeholder" clearable></up-input>
			</up-form-item>

			<view style="margin: 16px;">
				<up-button round block type="primary" @click="onSubmit">
					提交
				</up-button>
			</view>
		</up-form>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import myAxios from '@/plugins/myAxios'
	import {
		getCurrentUser
	} from '@/services/user'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const editUser = ref({
		editKey: '',
		editName: '',
		currentValue: '',
		placeholder: '',
	})

	// 获取页面参数
	onLoad((options) => {
		editUser.value = {
			editKey: options.editKey || '',
			editName: options.editName || '',
			currentValue: options.currentValue && options.currentValue !== 'undefined' ? options.currentValue :
				'',
			placeholder: options.placeholder || '',
		};
		console.log(editUser.value);
		console.log('options.editName:', options.editName);
	});


	// 表单提交处理
	const onSubmit = async () => {
		try {
			const currentUser = await getCurrentUser()
			if (!currentUser) {
				uni.showToast({
					title: '用户未登录',
					icon: 'none',
					duration: 2000,
				})
				return
			}
			console.log('用户信息:', currentUser)

			const res = await myAxios.post('/user/update', {
				id: currentUser.id,
				[editUser.value.editKey]: editUser.value.currentValue,
			})

			console.log('修改信息:', res)
			if (res.code === 0 && res.data > 0) {
				uni.showToast({
					title: '修改成功',
					icon: 'success',
					duration: 2000,
				})
				uni.navigateBack() // 返回上一页
			} else {
				uni.showToast({
					title: `修改失败: ${res.description || ''}`,
					icon: 'none',
					duration: 2000,
				})
			}
		} catch (error) {
			console.error('请求失败:', error)
			uni.showToast({
				title: '请求失败，请稍后再试',
				icon: 'none',
				duration: 2000,
			})
		}
	}
</script>

<style scoped>
	/* 样式调整 */
</style>